package cn.bdqn.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import cn.bdqn.util.ConfigManager;

public class BaseDao {
	/**获取数据库连接
	 * 
	 * @return
	 */
	public static Connection getConnetion(){
		Connection con = null;
		String driverClass = ConfigManager.getInstance().getString("jdbc.driver.class");
		String url = ConfigManager.getInstance().getString("jdbc.connection.url");
		String userName = ConfigManager.getInstance().getString("jdbc.connection.username");
		String password = ConfigManager.getInstance().getString("jdbc.connection.password");
		try {
			Class.forName(driverClass);
			con = DriverManager.getConnection(url, userName, password);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		/*try {
			Context context = new InitialContext();
			DataSource ds = (DataSource) context.lookup("java:comp/env/jsbc/smbms");
			con = ds.getConnection();
			
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
		return con;
	}
	//关闭资源
	public static void closeConnection(Connection con, PreparedStatement ps, ResultSet rs){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(ps != null ){
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(con != null){
			try{
				con.close();
			}catch( SQLException e){
				e.printStackTrace();
			}
		}
	}
	//增删改
	public static int execute(Connection con, PreparedStatement ps,  String sql, Object...params) throws SQLException{
		int row = 0;
		ps = con.prepareStatement(sql);
		//给sql语句中的？赋值
		for(int i=0; i<params.length; i++){
			ps.setObject(i+1, params[i]);
		}
		row = ps.executeUpdate();
	return row;
	}
	//查询数据
	public static ResultSet execute(Connection con, PreparedStatement ps, ResultSet rs, String sql, Object...params) throws SQLException{
		ps = con.prepareStatement(sql);
		//给sql语句中的？赋值
		for(int i=0; i<params.length; i++){
			ps.setObject(i+1, params[i]);
		}
		rs = ps.executeQuery();
	return rs;
	}

}
